package com.itheima.service.impl;

import com.itheima.mapper.NoteMapper;
import com.itheima.pojo.Brand;
import com.itheima.pojo.PageBean;
import com.itheima.service.BrandService;
import com.itheima.util.SqlSessionFactoryUtils;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;

import java.util.List;

public class BrandServiceImpl implements BrandService {
    //1.获取工厂对象
    SqlSessionFactory factory = SqlSessionFactoryUtils.getSqlSessionFactory();


    @Override
    public List<Brand> selectAll() {
        //2.获取sqlSession对象
        SqlSession sqlSession = factory.openSession();
        //3.获取BrandMapper
        NoteMapper mapper = sqlSession.getMapper(NoteMapper.class);
        //4.调用方法
        List<Brand> brands = mapper.selectAll();

        //5.释放资源
        sqlSession.close();
        return brands;
    }

    public void add(Brand brand){
        //2.获取sqlSession对象
        SqlSession sqlSession = factory.openSession();
        //3.获取BrandMapper
        NoteMapper mapper = sqlSession.getMapper(NoteMapper.class);
        //4.调用方法
        mapper.add(brand);
        sqlSession.commit();//提交事务
        //5.释放资源
        sqlSession.close();
    }

    @Override
    public PageBean<Brand> selectByPage(int currentPage, int pageSize) {
        //2.获取sqlSession对象
        SqlSession sqlSession = factory.openSession();
        //3.获取BrandMapper
        NoteMapper mapper = sqlSession.getMapper(NoteMapper.class);
        //4.查询总记录数
        int totoalCount = mapper.selectTotalCount();
        //5.计算开始索引
        int begin = pageSize * (currentPage - 1);
        int size = pageSize;
        //6.查询当前页数据
        List<Brand> rows = mapper.selectByPage(begin, size);

        //7.封装pageBean对象
        PageBean<Brand> pageBean = new PageBean<>();
        pageBean.setRows(rows);
        pageBean.setTotalCount(totoalCount);

        sqlSession.close();
        return pageBean;


    }
}
